package com.example.demo.web.controller;

import com.example.demo.bean.BaseRole;
import com.example.demo.service.IBaseRoleService;
import com.example.demo.utils.ExcelUtils;
import com.example.demo.utils.Message;
import com.example.demo.utils.MessageUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/baseRole")
@Validated
public class BaseRoleController {
    @Autowired
    private IBaseRoleService baseRoleService;
    @ApiOperation(value = "导入到Excel中", notes = "注意！测试的时候请将地址粘贴到浏览器地址栏测试", produces = "BaseRole/octet-stream")
    @GetMapping("download")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name") })
    public void download(HttpServletResponse response, String name) throws Exception {
        // 2. 将excel导出
        // 2.1 excel头部数据
        String[] headList = new String[] { "名称" };
        // 2.2 属性
        String[] fieldList = new String[] { "name" };
        // 2.3 数据列，需要转化
        List<Map<String, Object>> dataList = new ArrayList<>();
        List<BaseRole> list = baseRoleService.query(name);
        for (BaseRole baseRole : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", baseRole.getName());

            dataList.add(map);
        }
        // 2.4 导出文件名
        String excelName = "baseRole_Excel";
        // 3. 调用工具方法导出Excel
        ExcelUtils.createExcel(response, excelName, headList, fieldList, dataList);

    }
    @GetMapping("query")
    public Message query(String name) {
        List<BaseRole> list = baseRoleService.query(name);
        return MessageUtil.success(list);
    }

    @PostMapping("saveOrUpdate")
    public Message saveOrUpdate(BaseRole baseRole){
        baseRoleService.saveOrUpdate(baseRole);
        return MessageUtil.success("操作成功");
    }
    @DeleteMapping("deleteById")
    public Message deleteById(Long id){
        baseRoleService.deleteById(id);
        return MessageUtil.success("删除成功");
    }

}
